package com.dz.xjd.api;

import com.dz.xjd.app.App;
import com.dz.xjd.base.baserx.RxHelper;
import com.dz.xjd.base.baserx.RxSubscriber;
import com.dz.xjd.bean.Token;
import com.dz.xjd.params.Params;
import com.orhanobut.logger.Logger;
import java.util.ArrayList;

public class TokenManager {
    private static TokenManager mTokenManager ;
    private String token ;
    private ArrayList<onTokenChangeListener> mTokenChangeList = new ArrayList<>();

    public static TokenManager getInstance(){
        if (mTokenManager == null) {
            synchronized (TokenManager.class) {
                if (mTokenManager == null) {
                    mTokenManager = new TokenManager();
                }
            }
        }
        return mTokenManager;
    }

    public String getToken(){
        return token ;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public void requestToken(){
        Logger.d("重新获取token");
        ApiManage.getInstence().getApiService().getToken(Params.tokenHeadParams())
                .compose(RxHelper.<Token>handleResult())
                .subscribe(new RxSubscriber<Token>(false) {
                    @Override
                    protected void _onNext(Token tokenVo) {
                        token = tokenVo.getToken();
                        App.setToken(token);
                        Logger.d("重新获取token----"+token);
                        for (onTokenChangeListener listener : mTokenChangeList) {
                            listener.tokenChanged(tokenVo.getToken());
                        }
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                }) ;

    }

    public interface onTokenChangeListener {
        public void tokenChanged(String token);
    }

    public void addTokenChangeListener (onTokenChangeListener listener){
        if (!mTokenChangeList.contains(listener)) {
           
            mTokenChangeList.add(listener);
        }
    }

    public void removeTokenChangeListener (onTokenChangeListener listener){
        if (mTokenChangeList.contains(listener))
             mTokenChangeList.remove(listener);
        Logger.d("removeTokenChangeListener----");
    }

}
